package com.qnnproject

import android.util.Log
import com.facebook.react.bridge.*
import com.facebook.react.modules.core.DeviceEventManagerModule
import kotlinx.coroutines.*

class RabbitMQModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
    
    companion object {
        private const val TAG = "RabbitMQModule"
    }
    
    private var rabbitMQService: RabbitMQService? = null
    private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    
    override fun getName(): String {
        return "RabbitMQModule"
    }
    
    @ReactMethod
    fun startRabbitMQ(promise: Promise) {
        try {
            Log.d(TAG, "启动RabbitMQ服务")
            
            rabbitMQService = RabbitMQService(reactApplicationContext) { message ->
                // 当收到消息时，发送事件到React Native
                sendEvent("onMessageReceived", Arguments.createMap().apply {
                    putString("phone", message.phone)
                    putString("deviceId", message.deviceId)
                    putString("time", message.time)
                })
            }
            
            scope.launch {
                rabbitMQService?.connect()
                withContext(Dispatchers.Main) {
                    promise.resolve("RabbitMQ服务启动成功")
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "启动RabbitMQ服务失败", e)
            promise.reject("RABBITMQ_ERROR", "启动RabbitMQ服务失败: ${e.message}")
        }
    }
    
    @ReactMethod
    fun stopRabbitMQ(promise: Promise) {
        try {
            Log.d(TAG, "停止RabbitMQ服务")
            rabbitMQService?.disconnect()
            rabbitMQService = null
            promise.resolve("RabbitMQ服务已停止")
        } catch (e: Exception) {
            Log.e(TAG, "停止RabbitMQ服务失败", e)
            promise.reject("RABBITMQ_ERROR", "停止RabbitMQ服务失败: ${e.message}")
        }
    }
    
    @ReactMethod
    fun getDeviceId(promise: Promise) {
        try {
            val deviceId = rabbitMQService?.getDeviceId() ?: DeviceIdManager(reactApplicationContext).getDeviceId()
            promise.resolve(deviceId)
        } catch (e: Exception) {
            Log.e(TAG, "获取设备ID失败", e)
            promise.reject("DEVICE_ID_ERROR", "获取设备ID失败: ${e.message}")
        }
    }
    
    @ReactMethod
    fun getQueueName(promise: Promise) {
        try {
            val queueName = rabbitMQService?.getQueueName() ?: DeviceIdManager(reactApplicationContext).getQueueName()
            promise.resolve(queueName)
        } catch (e: Exception) {
            Log.e(TAG, "获取队列名称失败", e)
            promise.reject("QUEUE_NAME_ERROR", "获取队列名称失败: ${e.message}")
        }
    }
    
    @ReactMethod
    fun isConnected(promise: Promise) {
        try {
            val connected = rabbitMQService?.isConnected() ?: false
            promise.resolve(connected)
        } catch (e: Exception) {
            Log.e(TAG, "检查连接状态失败", e)
            promise.reject("CONNECTION_ERROR", "检查连接状态失败: ${e.message}")
        }
    }
    
    @ReactMethod
    fun setDeviceId(deviceId: String, promise: Promise) {
        try {
            DeviceIdManager(reactApplicationContext).setDeviceId(deviceId)
            promise.resolve("设备ID设置成功")
        } catch (e: Exception) {
            Log.e(TAG, "设置设备ID失败", e)
            promise.reject("DEVICE_ID_ERROR", "设置设备ID失败: ${e.message}")
        }
    }
    
    private fun sendEvent(eventName: String, params: WritableMap?) {
        reactApplicationContext
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
            .emit(eventName, params)
    }
    
    override fun onCatalystInstanceDestroy() {
        super.onCatalystInstanceDestroy()
        scope.cancel()
        rabbitMQService?.disconnect()
    }
}
